/**
 * Copyright(c) kyle.
 */
package org.example.jvm.remote_executor;

/**
 * 数组处理工具
 *
 * @author kyle
 * @version 1.00.00
 * @since [2020-12-05 15:34]
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2020-12-05 15:34]
 */
public final class ByteUitls {
    public static String bytes2String(byte[] b, int start, int len) {
        return new String(b, start, len);
    }

    public static byte[] string2Bytes(String str) {
        return str.getBytes();
    }

    public static int bytes2Int(byte[] b, int start, int len) {
        int sum = 0;
        int end = start + len;
        for (int i = start; i < end; i++) {
            int n = ((int) b[i]) & 0xff;
            n <<= (--len) * 8;
            sum = n + sum;
        }
        return sum;
    }

    public static byte[] int2Bytes(int value, int len) {
        byte[] b = new byte[len];
        for (int i = 0; i < len; i++) {
            b[len - i - 1] = (byte) ((value >> 8 * i) & 0xff);
        }
        return b;
    }

    /**
     * 保留originalBytes两端的字节，
     * 替换起始点为offset，长度为len的字节
     *
     * @param originalBytes 原字节码
     * @param offset        偏移量
     * @param len           长度
     * @param repalceBytes  替换字节
     * @return
     */
    public static byte[] bytesReplace(byte[] originalBytes, int offset, int len, byte[] repalceBytes) {
        byte[] newBytes = new byte[originalBytes.length + (repalceBytes.length - len)];
        System.arraycopy(originalBytes, 0, newBytes, 0, offset);
        System.arraycopy(repalceBytes, 0, newBytes, offset, repalceBytes.length);
        System.arraycopy(originalBytes, offset + len,
                newBytes, offset + repalceBytes.length,
                originalBytes.length - offset - len);
        return newBytes;
    }
}
